package org.jeecg.modules.network.network.tcp;

import com.zhouwr.common.device.vo.function.InstanceFunctionVo;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

/**
 * @program: forallcn-iotps
 * @description: tcp同步请求
 * @author: zhouwr
 * @create: 2021-02-23 21:12
 * @version：1.0
 **/
@Slf4j
public class TcpSyncRequestUtil {

    /**
     * @param ctx
     * @param key
     * @param executeConfig
     * @param timeout
     * @return
     */
    public static Object get(ChannelHandlerContext ctx, String key, InstanceFunctionVo executeConfig, long timeout) {
        if (ctx == null) {
            log.error("没有获取连接通道，终止执行功能！");
            return null;
        }
        log.info("返回类型 >>>>>>> {}", executeConfig.getOutputParam());
        Channel channel = ctx.channel();
        synchronized (channel) {
            AttributeKey<Object> attrKey = AttributeKey.valueOf(key);
            Attribute<Object> attribute = channel.attr(attrKey);
            synchronized (attribute) {
                channel.writeAndFlush(executeConfig);
                try {
                    attribute.wait(timeout);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return attribute.get();
            }
        }
    }

    public static void set(ChannelHandlerContext ctx, String key, Object msg) {
        AttributeKey<Object> attrKey = AttributeKey.valueOf(key);
        log.info("channel.hasAttr(attrKey) >>>>> {}", ctx.channel().hasAttr(attrKey));
        if (ctx.channel().hasAttr(attrKey)) {
            Attribute<Object> attribute = ctx.channel().attr(attrKey);
            synchronized (attribute) {
                attribute.set(msg);
                attribute.notify();
            }
        }
    }
}
